import Vue from 'vue'
import store from '@/store'
import VueRouter from 'vue-router'

const Login = () => import('@/views/login/index.vue')
const Layout = () => import('@/views/layout/index.vue')
const Home = () => import('@/views/home/index.vue')
const Question = () => import('@/views/question/index.vue')
const Addwork = () => import('@/views/question/work.vue')
const DetailsWork = () => import('@/views/question/details.vue')
const DetailsTask = () => import('@/views/task/details.vue')
const Task = () => import('@/views/task/index.vue')
const User = () => import('@/views/user/index.vue')
const Search = () => import('@/views/search/index.vue')
const SearchResult = () => import('@/views/search/result.vue')
const Article = () => import('@/views/article/index.vue')
const Profile = () => import('@/views/user/profile.vue')
const UserChat = () => import('@/views/user/chat.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: Question, meta: { isKeepAlive: true } },
        { path: '/question', component: Question },
        { path: '/task', component: Task },
        { path: '/user', component: User },
        { path: '/question/addWork', component: Addwork },
        { path: '/question/details', component: DetailsWork },
        { path: '/task/details', component: DetailsTask }
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchResult', component: SearchResult },
    { path: '/article/:id', component: Article },
    { path: '/profile', component: Profile },
    { path: '/userChat', component: UserChat }
  ]
})

// 需要认证的页面
const AuthUrls = ['/user', '/question/addWork', '/task']
router.beforeEach((to, from, next) => {
  if (to.path === '/login' && store.state.tokenInfo.token) {
    next('/')
    return
  }

  // 如果是需要授权的页面
  if (AuthUrls.includes(to.path)) {
    // 进行验证身份
    if (store.state.tokenInfo.token) {
      next()
    } else {
      // 拦截到登录
      next({
        path: '/login',
        query: {
          backto: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})
export default router
